<script setup lang="ts">
import {Feature, Map, View} from "ol";
import * as control from 'ol/control';
import * as coordinate from 'ol/coordinate';
import TileLayer from "ol/layer/Tile";
import LayerVector from 'ol/layer/Vector'
import SourceVector from 'ol/source/Vector'
import Draw from 'ol/interaction/Draw'
import {XYZ} from "ol/source";
import {onMounted, reactive, ref} from "vue";
import source = ol.source;
import {currentPoints, currentPointsNull, TaskForm, tempTaskAssign} from "../store/taskStore.ts";
import * as geom from "ol/geom";
import html2canvas from "html2canvas";
import {getTaskById, updateTask} from "../network/taskApi.ts";


const map = ref(null) // 存放地图实例
const mousePositionTxt = ref([102.064839, 24.548857])
const currentCoordinate = ref([102.064839, 24.548857])
const scaleLineControl = ref(null) //比例尺
let coordinateSign = ref(0) //是否显示经纬度
const tool = ref('Polygon')
let points = ref(null)

const emit = defineEmits(['draw-change-sign'])


type Props = {
  taskId: number
}
let prop = defineProps<Props>()
let taskForm = reactive<TaskForm>({})

const sourceDraw = new SourceVector({
  wrapX: false, // 禁止横向无限重复（底图渲染的时候会横向无限重复），设置了这个属性，可以让绘制的图形不跟随底图横向无限重复
})

// 绘图层
let vector = new LayerVector({
  source: sourceDraw,
})

function initMap () {
  scaleLineControl.value = new control.ScaleLine()//默认是 米制单位
  // 地图实例
  map.value = new Map({
    target: 'map1',                         // 对应页面里 id 为 map1 的元素
    layers: [                              // 图层
      new TileLayer({
        source: new XYZ({
          url:"http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=f0205b3015ed23553ee037f6ecac9b19",
          wrapX: false,
          crossOrigin: 'anonymous'
        }),
        preload: Infinity,//底图预加载。减少缩放时出现的空白区域。
      }),
      new TileLayer({
        source: new XYZ({
          url:"http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=f0205b3015ed23553ee037f6ecac9b19",
          wrapX: false,
          crossOrigin: 'anonymous'

        }),
        preload: Infinity,
      }),
      vector,

    ],
    view: new View({                       // 地图视图
      projection: "EPSG:4326",             // 坐标系，有EPSG:4326和EPSG:3857
      center: [102.8599, 24.8297],     // 深圳坐标（经纬度）
      minZoom:2,// 地图缩放最小级别
      maxZoom:18,//同时设置这两个值（min、maxZoom）之后，就能够限制缩放
      zoom: 15                             // 地图默认缩放级别（打开页面时默认级别）
    }),
    controls: control.defaults().extend([
      scaleLineControl.value, // 比例尺
      new control.MousePosition({
        coordinateFormat: coordinate.createStringXY(4),
        projection: 'EPSG:4326',
        target: mousePositionTxt.value
      })
    ])
  })
}
const draw = ref(null)

function drawPoly() {
  if (draw.value != null) {
    map.value.removeInteraction(draw.value)
  }
  if (tool.value != 'None') {
    draw.value = new Draw({
      source: sourceDraw,
      type: tool.value
    })
    map.value.addInteraction(draw.value)
    //当图形框选完之后，就会执行下面，输出点
    draw.value.on('drawend', function (event){
      let geometry = event.feature.getGeometry()
      points.value = geometry.getCoordinates()[0]
      points.value.forEach(point=>{
        currentPoints.push(point)
      })
      console.log(currentPoints)


      let task = ref({id: prop.taskId})
      getTaskById(task.value).then(res=>{
        if(res.data.code == 0) {
          for (let taskFormKey in res.data.data) {
            taskForm[taskFormKey] = res.data.data[taskFormKey]
          }
          taskForm.points = currentPoints
          exportAction()
        }
        else{
          console.log("MapComponent 出现问题")
        }

      })
    })
  }
}

function drawExit() {
  if (draw.value) {
    map.value.removeInteraction(draw.value);
  }
  draw.value = null
}

function drawClear() {
  //用于清空 绘制层
  while(currentPoints.length>0){
    currentPoints.forEach(point=>{
      currentPoints.pop(point)
    })
  }
  console.log(currentPoints)
  sourceDraw.clear()
  console.log(sourceDraw)

  let task = ref({id: prop.taskId})
  getTaskById(task.value).then(res=> {
    if (res.data.code == 0) {
      for (let taskFormKey in res.data.data) {
        taskForm[taskFormKey] = res.data.data[taskFormKey]
      }
      taskForm.points = tempTaskAssign.points
      taskForm.mapCode = tempTaskAssign.mapCode
      console.log(taskForm)
      updateTask(taskForm).then(res=>{
        console.log(res.data.message)
        // console.log(taskForm)
        emit('draw-change-sign',true)
      })
    }
  })
}


const exportAction = () =>{
  download();
}
const download = () => {
  let targetDom = document.getElementById("map-component"); //原本需要截图的div
  console.log("🚀 ~ file: index.vue:33 ~ download ~ targetDom:", targetDom.clientWidth)
  let clonedNode = targetDom.cloneNode(true); //复制一个
  clonedNode.setAttribute(
      "style",
      `width: ${targetDom.clientHeight};height: ${targetDom.clientWidth};`
  );
  document.body.appendChild(clonedNode); //放到body后面
  // 转换成canvas
  html2canvas(targetDom, {
    allowTaint: true,
    taintTest: false,
    useCORS: true,
    background: "#ffffff", // 一定要添加背景颜色，否则出来的图片，背景全部都是透明的
    //图相对小，但是很好存
    scale: 0.1,
    dpi: 10
    //清晰设置：
    // scale: 2, // 处理模糊问题
    // dpi: 300, // 处理模糊问题
  }).then(function (canvas) {
    var pageData = canvas.toDataURL("image/png", 1.0);
    taskForm.mapCode = pageData
    document.body.removeChild(clonedNode);

    updateTask(taskForm).then(res=>{
      console.log(res.data.message)
      // console.log(taskForm)
      emit('draw-change-sign',true)
    })
  });
};


onMounted(() => {
  initMap()
})



function showCoordinate(){
  coordinateSign.value = 1
}
</script>

<template>
  <div class="flex w-full gap-1">
    <div id="map1" tabindex="2" class="map1__x grow h-full
    bg-#84b9bf relative" @click="showCoordinate">
<!--      <div class="absolute z-10 bg-white rounded-lg px-2 py-1 bottom-1 right-1">经度：{{currentCoordinate[0]}} &nbsp;纬度：{{currentCoordinate[1]}}</div>-->
      <div class="draw-buttons absolute z-11 h-9 flex justify-start items-center bottom-1 right-60" v-show="coordinateSign==1">
        <button @click="drawPoly">绘制区域</button>
        <button @click="drawExit">退出绘制</button>
        <button @click="drawClear">清空绘制</button>
      </div>
      <div class="absolute z-10 w-50 h-9 bg-white rounded-lg px-2  bottom-1 right-1 flex justify-start items-center" ref="mousePositionTxt" v-show="coordinateSign==1">经纬度：</div>

    </div>

  </div>


</template>

<style scoped>

</style>